package com.filter;

import com.beans.AdminInfo;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "SessionFilter")
public class SessionFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request =(HttpServletRequest)req;
        HttpSession session = request.getSession();
        String uri = request.getRequestURI();
        String contextPath = request.getContextPath();

        if (uri.contains("login.jsp")||uri.equals(contextPath+"/")){
            chain.doFilter(req,resp);
        }else {
            AdminInfo admin = (AdminInfo) session.getAttribute("session_admin");
            if (admin==null){
                resp.getWriter().print("<script>window.top.location.href='login.jsp'</script>");
            }else {
                chain.doFilter(req, resp);
            }
        }
    }
}
